package com.item.news.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.item.news.config.JedisConfig;
import com.item.news.runnable.Video_ScreenshotsRunnable;
import com.item.news.util.HttpClient;
import com.item.news.util.StringEncode;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;
import sun.misc.BASE64Encoder;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.*;

/**
 * @ClassName IndexController
 * @Description TODO
 * @Author WangDong
 * @Date 2019/1/18 10:01
 * @Version 1.0
 **/
@RestController
@RequestMapping("/")
public class IndexController {

    @RequestMapping("/index")
    public JSONArray index(HttpServletRequest request) {
       String name= request.getParameter("name");
        System.out.println("这是name:"+name);

       Jedis jedis= new JedisConfig().getJedis();
        JSONArray data=null;
       switch (name){
           case "toutiao":
               data= JSON.parseArray(jedis.get("toutiao"));
           break;
           case "shandong":
               //System.out.println(jedis.get("shandong"));
               data= JSON.parseArray(jedis.get("shandong"));
               break;
           case "guonei":
               data= JSON.parseArray(jedis.get("guonei"));
               break;
           case "guoji":
               data= JSON.parseArray(jedis.get("guoji"));
               break;
           case "yvle":
               data= JSON.parseArray(jedis.get("yvle"));
               break;
           case "dianying":
               data= JSON.parseArray(jedis.get("dianying"));
               break;
           case "hangkong":
               data= JSON.parseArray(jedis.get("hangkong"));
               break;
           case "jiankang":
               data= JSON.parseArray(jedis.get("jiankang"));
               break;
           case "lvyou":
               data= JSON.parseArray(jedis.get("lvyou"));
               break;
           case "jiaoyv":
               data= JSON.parseArray(jedis.get("jiaoyv"));
               break;
       }
        return data;
    }






    @RequestMapping("/openInfo")
    public String openInfo(HttpServletRequest request){
        String url = request.getParameter("url");
        // String url = "http://news.qingdaonews.com/zonghe/";
        String data="";
        try {
            Document doc = Jsoup.connect(url).get();
            Elements body = doc.select(" div[class=\"g-box-7\"] "); //带有href属性的a元素
            Elements title = doc.select(" h1[class=\"m-tt-1\"] "); //带有href属性的a元素
            Elements newsinfo = doc.select(" div[class=\"g-box-2 mb30\"]>div[class=\"m-msg-1\"]>span"); //带有href属性的a元素
            Elements content = doc.select(" div[class=\"g-box-3 fl\"]>div[ class=\"m-ct mb80\"]>p"); //带有href属性的a元素
           /* System.out.println("这是数据："+body);*/
            data= title.toString()+newsinfo.toString()+content.toString();
            data=data.replaceAll("<img","<img style='width:90%'");
            data=data.replaceAll("<h1","<h1 style='font-size: 1.5em;'");
            /*System.out.println("这是小信息："+newsinfo);
            System.out.println("内容："+content);*/
            //System.out.println("这是数据："+data);
            System.out.println("获取新闻信息");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return data;
    }

    @RequestMapping("/top_news")
    public List<HashMap<String,String>> top_news() {
        String url = "https://www.163.com/";
        List<HashMap<String,String>> data=new ArrayList<HashMap<String,String>>();
        try {
            Document doc = Jsoup.connect(url).get();
            System.out.println("获取头条信息");
           // System.out.println("这是数据：" + doc);

            Elements top_news = doc.select(" div.news_bj_yw>ul.cm_ul_round>li"); //带有href属性的a元素
             for (Element e: top_news){
                HashMap<String,String> maps=new HashMap<String,String>();
                maps.put("title",e.select("a").text());
                 String href= e.select("a").attr("href");
                 href=href.substring(href.length()-4,href.length());
                 if(href.equals("html")){
                    // System.out.println(e.select("a").attr("href"));
                     maps.put("href",e.select("a").attr("href"));
                 }

                maps.put("tag","");
                maps.put("img","");
                data.add(maps);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        Jedis jedis = new Jedis("localhost");
        System.out.println("连接成功");
        //设置 redis 字符串数据
        jedis.set("news", data.toString());
        // 获取存储的数据并输出
        return data;
    }

    @RequestMapping("/news_ohter")
    public List<HashMap<String,String>> news_ohter(HttpServletRequest request){
        System.out.println("获取其他新闻");
        String url = request.getParameter("url");
        List<HashMap<String,String>> data=new ArrayList<HashMap<String,String>>();
        try {
            //构造一个webClient 模拟Chrome 浏览器
            WebClient webClient = new WebClient(BrowserVersion.CHROME);
            //屏蔽日志信息
           /* LogFactory.getFactory().setAttribute("org.apache.commons.logging.Log","org.apache.commons.logging.impl.NoOpLog");
            java.util.logging.Logger.getLogger("com.gargoylesoftware").setLevel(Level.OFF);
            java.util.logging.Logger.getLogger("org.apache.http.client").setLevel(Level.OFF);
*/

            //支持JavaScript
            webClient.getOptions().setJavaScriptEnabled(true);
            webClient.getOptions().setCssEnabled(false);
            webClient.getOptions().setActiveXNative(false);
            webClient.getOptions().setCssEnabled(false);
            webClient.getOptions().setThrowExceptionOnScriptError(false);
            webClient.getOptions().setThrowExceptionOnFailingStatusCode(false);
            webClient.getOptions().setTimeout(0);
            HtmlPage rootPage = webClient.getPage(url);
            //设置一个运行JavaScript的时间
            webClient.waitForBackgroundJavaScript(3000);
            String html = rootPage.asXml();
            Document doc = Jsoup.parse(html);
          /*  System.out.println(doc);*/
            Elements img=doc.select("div.data_row > a >img");
            Elements title=doc.select("div.news_title > h3 >a");
            Elements tag=doc.select("div.news_tag > div.keywords ");
            Elements time=doc.select("div.news_tag > span.time");
            /*System.out.println("这是数据"+img);
            System.out.println("这是数据"+title);
            System.out.println("这是数据"+tag);
            System.out.println("这是数据"+time);*/

            for(int i=0;i<title.size();i++){
                HashMap<String,String>maps=new HashMap<String,String>();
                title.eq(i).select("a").text();
                img.eq(i).select("img").attr("src");
                img.eq(i).select("img").attr("href");
                tag.eq(i).select("div").select("a").text();
                maps.put("title", title.eq(i).select("a").text());
                maps.put("img",img.eq(i).select("img").attr("src"));
                maps.put("href",title.eq(i).select("a").attr("href"));
                maps.put("tag",tag.eq(i).select("div").select("a").text());
                maps.put("time",time.eq(i).select("span").text());
                data.add(maps);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return data;
    }

    @RequestMapping("/news_sd")
    public List<HashMap<String,String>> news_sd(HttpServletRequest request){
        System.out.println("获取山东新闻");
        String url = request.getParameter("url");
        List<HashMap<String,String>> data=new ArrayList<HashMap<String,String>>();
        try {
            //构造一个webClient 模拟Chrome 浏览器
            WebClient webClient = new WebClient(BrowserVersion.CHROME);
            //屏蔽日志信息

            //支持JavaScript
            webClient.getOptions().setJavaScriptEnabled(true);
            webClient.getOptions().setCssEnabled(false);
            webClient.getOptions().setActiveXNative(false);
            webClient.getOptions().setCssEnabled(false);
            webClient.getOptions().setThrowExceptionOnScriptError(false);
            webClient.getOptions().setThrowExceptionOnFailingStatusCode(false);
            webClient.getOptions().setTimeout(0);
            HtmlPage rootPage = webClient.getPage(url);
            //设置一个运行JavaScript的时间
            webClient.waitForBackgroundJavaScript(3000);
            String html = rootPage.asXml();
            Document doc = Jsoup.parse(html);
            System.out.println(doc);
            Elements img=doc.select("div.news-left > a >img");
            Elements title=doc.select("p.nr-tit > a");
            Elements tag=doc.select("div.nr-cont > a ");
            /*  Elements time=doc.select("div.news_tag > span.time");*/
            //System.out.println("这是数据"+img);
            //System.out.println("这是数据"+title);
            //System.out.println("这是数据"+tag);
            /*  System.out.println("这是数据"+time);*/

            for(int i=0;i<title.size();i++){
                HashMap<String,String>maps=new HashMap<String,String>();
               /* title.eq(i).select("a").text();
                img.eq(i).select("img").attr("src");
                img.eq(i).select("img").attr("href");
                tag.eq(i).select("div").select("a").text();*/
                maps.put("title", title.eq(i).select("a").text());
                maps.put("img",img.eq(i).select("img").attr("src"));
                maps.put("href",title.eq(i).select("a").attr("href"));
                maps.put("tag",tag.eq(i).select("div").select("a").text());
                maps.put("time","");
                data.add(maps);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
           return data;
    }
    @RequestMapping("/news_yl")
    public  List<HashMap<String,String>> news_yl(HttpServletRequest request){
        String url = request.getParameter("url");
        System.out.println("获取娱乐新闻");
        List<HashMap<String,String>> data=new ArrayList<HashMap<String,String>>();
        try {
            //构造一个webClient 模拟Chrome 浏览器
            WebClient webClient = new WebClient(BrowserVersion.CHROME);
            //屏蔽日志信息

            //支持JavaScript
            webClient.getOptions().setJavaScriptEnabled(true);
            webClient.getOptions().setCssEnabled(false);
            webClient.getOptions().setActiveXNative(false);
            webClient.getOptions().setCssEnabled(false);
            webClient.getOptions().setThrowExceptionOnScriptError(false);
            webClient.getOptions().setThrowExceptionOnFailingStatusCode(false);
            webClient.getOptions().setTimeout(5000);
            HtmlPage rootPage = webClient.getPage(url);
            //设置一个运行JavaScript的时间
            webClient.waitForBackgroundJavaScript(5000);
            String html = rootPage.asXml();
            Document doc = Jsoup.parse(html);
           // System.out.println(doc);
            Elements img=doc.select("div.clearfix > a >img");
            Elements title=doc.select("h3.bigsize > a");
            Elements tag=doc.select("p.sourceDate");



            for(int i=0;i<title.size();i++){
                HashMap<String,String>maps=new HashMap<String,String>();

                maps.put("title", title.eq(i).select("a").text());
                maps.put("img",img.eq(i).select("img").attr("src"));
                maps.put("href",title.eq(i).select("a").attr("href"));
                maps.put("tag",tag.eq(i).select("div").select("a").text());
                data.add(maps);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return data;
    }

    @RequestMapping("/newsInfo")
    public String newsInfo(HttpServletRequest request){
        String url = request.getParameter("url");
        String data="";
        try {
            Document doc = Jsoup.connect(url).get();

            //System.out.println("这是数据："+doc);
            Elements body = doc.select(" div.post_text#endText"); //带有href属性的a元素

            if(body.size()<1){
                body = doc.select(" div#content"); //带有href属性的a元素
            }
            data=body.toString();
            data=data.replaceAll("<img","<img style='width:96%'");

           // System.out.println("这是摘要："+body);
            /*  System.out.println("这是摘要："+top_news2);*/


        } catch (IOException e) {
            e.printStackTrace();
        }
        return data;
    }
    @RequestMapping("/news_Load")
    public List<HashMap<String,String>> news_Load(HttpServletRequest request){
        System.out.println("获取新闻加载");
        String url = request.getParameter("url");
       // String url = "http://temp.163.com/special/00804KVA/cm_guonei_02.js?callback=data_callback";
        List<HashMap<String,String>> data=new ArrayList<HashMap<String,String>>();
        try {
            //构造一个webClient 模拟Chrome 浏览器
            WebClient webClient = new WebClient(BrowserVersion.CHROME);
            //屏蔽日志信息

            //支持JavaScript
            webClient.getOptions().setJavaScriptEnabled(true);
            webClient.getOptions().setCssEnabled(false);
            webClient.getOptions().setActiveXNative(false);
            webClient.getOptions().setCssEnabled(false);
            webClient.getOptions().setThrowExceptionOnScriptError(false);
            webClient.getOptions().setThrowExceptionOnFailingStatusCode(false);
            webClient.getOptions().setTimeout(5000);
            HtmlPage rootPage = webClient.getPage(url);
            //设置一个运行JavaScript的时间
            webClient.waitForBackgroundJavaScript(5000);
            String html = rootPage.asXml();
            Document doc = Jsoup.parse(html);
            Elements body=doc.select("body");
            String result=StringEncode.toUTF8(body.text());
            result=result.substring(result.indexOf("(")+1,result.lastIndexOf(")"));
            JSONArray array=JSONArray.parseArray(result);
            //System.out.println(array.toString());
            String tag="";
            for(int i=0;i<array.size();i++){
                HashMap<String,String>maps=new HashMap<String,String>();
                JSONObject object=JSONObject.parseObject(array.get(i).toString());
                JSONArray keywords=JSONArray.parseArray(JSONObject.parseObject(array.get(i).toString()).getString("keywords"));

                tag="";
                for(int j=0;j<keywords.size();j++){
                    tag+=JSONObject.parseObject(keywords.get(j).toString()).getString("keyname")+" ";
                }
                maps.put("tag",tag);
                maps.put("title",object.getString("title"));
                maps.put("href",object.getString("docurl"));
                maps.put("img",object.getString("imgurl"));
                maps.put("time",object.getString("time"));
                data.add(maps);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
      return data;
    }

    @RequestMapping("/getVideo")
    public  List<HashMap<String,String>> getVideo(){
        List<HashMap<String,String>> data=new ArrayList<HashMap<String,String>>();
        String url="http://api.ksapisrv.com/rest/n/feed/hot?mod=Hisense%28HLTE501N%29&lon=120.42882&country_code=cn&extId=88b56a5448dde3c6609bf08c05278c52&did=ANDROID_7c510180b53c91b7&net=WIFI&app=0&oc=APPCHINA_CPD&ud=0&c=APPCHINA_CPD&sys=ANDROID_7.1.1&appver=5.9.1.6830&ftt=&language=zh-cn&iuid=DuORsqPtoxzJgSgykmmyNyazNyugobf7utc7rcpHPgrBbzqCOnusvbWwQFbtvmk2Qx7asBntqE7aK997YjZdFV5A&lat=36.1476&ver=5.9&did_gt=1539061014057&max_memory=256&type=7&page=2&coldStart=false&count=20&pv=false&id=49&refreshTimes=1&pcursor=&source=1&client_key=3c2cd3f3&os=android&sig=7c5a2c74cd3948fcf5b35481d61a1b94";
        String result = HttpClient.doGet(url);
        JSONObject object=JSONObject.parseObject(result);
        JSONArray array=JSONArray.parseArray(object.getString("feeds"));
        System.out.println("获取视频");
        //System.out.println(array);
        try {
            String ffmpeg_path="C:/news/ffmpeg.exe";

        for(int i=0;i<array.size();i++){
            JSONArray  main_mv_urls =JSONArray.parseArray(JSONObject.parseObject(array.get(i).toString()).getString("main_mv_urls")) ;
            String caption=JSONObject.parseObject(array.get(i).toString()).getString("caption");
            //System.out.println(caption);
            if(main_mv_urls!=null){
                HashMap<String,String>maps=new HashMap<String,String>();
                String mv=  JSONObject.parseObject(main_mv_urls.get(1).toString()).getString("url");
                //System.out.println("这是路径："+mv);
                mv=mv.substring(0,mv.lastIndexOf("?"));
                maps.put("mv_url",mv);
                String imgurl=UUID.randomUUID().toString().replace("-", "")+".jpg";
                new Thread(new Video_ScreenshotsRunnable(mv,imgurl)).start();
               /* transfer(mv, imgurl,"1");*/
                maps.put("img_url","http://106.13.79.84:8888/"+imgurl);
                maps.put("caption",caption);
                data.add(maps);
            }
        }
    }catch (Exception e){

    }
        return data;

    }


    /**
     * @Author WangDong
     * @Description //TODO Linux截图
     * @Date 2019/1/21 15:21
     * @Param [inFile, outFile, startTime]
     * @return boolean
     *
     **/
    public static boolean transfer(String inFile, String outFile,String startTime) {


        String command = "ffmpeg -i " + inFile
                + " -y -f image2 -ss "+startTime+" -t 00:00:01 -s  720x1280 "
                + outFile;
        try {
            Runtime rt = Runtime.getRuntime();
            Process proc = rt.exec(command);
            InputStream stderr = proc.getErrorStream();
            InputStreamReader isr = new InputStreamReader(stderr);
            BufferedReader br = new BufferedReader(isr);
            String line = null;
            while ((line = br.readLine()) != null)
                System.out.println(line);
        } catch (Throwable t) {
            t.printStackTrace();
            return false;
        }
        return true;
    }



    /**
     * @Author WangDong
     * @Description //TODO win截图
     * @Date 2019/1/21 15:21
     * @Param [veido_path, ffmpeg_path]
     * @return java.lang.String
     *
     **/
    public static String processImg(String veido_path, String ffmpeg_path) {

        List<String> commands = new ArrayList<String>();
        commands.add(ffmpeg_path);
        commands.add("-i");
        commands.add(veido_path);
        commands.add("-y");
        commands.add("-f");
        commands.add("image2");
        commands.add("-ss");
        commands.add("8");// 这个参数是设置截取视频多少秒时的画面
        // commands.add("-t");
        // commands.add("0.001");
        commands.add("-s");
        String base64url="";
        try {
            commands.add("720x1280");
            String url="F:/news/img/";
            // judeDirExists(new File(url));

            File file = new File(url);
            if(!file.exists()){
                file.mkdirs();
            }
            url= url+"jj.JPG";
            commands.add(url);

            ProcessBuilder builder = new ProcessBuilder();
            builder.command(commands);
            builder.start();
            System.out.println("截取成功");
            base64url=ImageToBase64ByLocal(url);
           // System.out.println(base64url);

        } catch (Exception e) {
            e.printStackTrace();

        }
        return base64url;
    }
    public static String ImageToBase64ByLocal(String imgFile) {
        // 将图片文件转化为字节数组字符串，并对其进行Base64编码处理
        InputStream in = null;
        byte[] data = null;

        // 读取图片字节数组
        try {
            in = new FileInputStream(imgFile);

            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 对字节数组Base64编码
        BASE64Encoder encoder = new BASE64Encoder();

        return encoder.encode(data);// 返回Base64编码过的字节数组字符串
    }

}
